﻿
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using static Vboot.App.MsgHelper;

namespace Vboot.App.K3CloudDataSend
{
    public class HttpClient
    {
        ///
        /// Seivice URL
        ///
        public string Url { get; set; }
        ///
        /// 内容
        ///
        public string Content { get; set; }
        ///
        /// Cookie，保证登录后，所有访问持有一个Cookie；
        ///
        static CookieContainer Cookie = new CookieContainer();

        /// 
        /// HTTP访问
        /// 
        public string AsyncRequest()
        {
            HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min

            using (Stream reqStream = httpRequest.GetRequestStream())
            {
                JObject jObj = new JObject();
                jObj.Add("format", 1);
                jObj.Add("useragent", "ApiClient");
                jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                jObj.Add("parameters", Content);
                jObj.Add("timestamp", DateTime.Now);
                jObj.Add("v", "1.0");
                string sContent = jObj.ToString();
                var bytes = UnicodeEncoding.UTF8.GetBytes(sContent);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            using (var repStream = httpRequest.GetResponse().GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }

        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                return responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }
    

        public List<object> UnAuditFormat(List<string> fbillnos, string formid)
        {
            List<object> Parameters = new List<object>();
            string datas = "";
            Parameters.Add(formid);
            foreach (var item in fbillnos)
            {
                datas += "\"" + item + "\"" + ",";
            }
            datas = datas.Substring(0, datas.Length - 1);
            string data = "{\"Numbers\":[" + datas + "]}";
            Parameters.Add(data);
            return Parameters;
        }
        public List<object> UnAuditFormatStrings(string fbillnos, string formid)
        {
            List<object> Parameters = new List<object>();
            string datas = "";
            Parameters.Add(formid);
            string data = "{\"Numbers\":[" + fbillnos + "]}";
            Parameters.Add(data);
            return Parameters;
        }
        public List<object> Format(string result1, string formid)
        {
            List<object> Parameters = new List<object>();
            Root msg = JsonConvert.DeserializeObject<Root>(result1);
            string saveresult = "", datas = "";
            foreach (var item in msg.Result.ResponseStatus.SuccessEntitys)
            {
                saveresult += item.Number + ",";
            }
            string number = saveresult.Substring(0, saveresult.Length - 1);
            var list = number.Split(',').ToList();
            Parameters.Add(formid);
            foreach (var item in list)
            {
                datas += "\"" + item + "\"" + ",";
            }
            datas = datas.Substring(0, datas.Length - 1);
            string data = "{\"Numbers\":[" + datas + "]}";
            Parameters.Add(data);
            return Parameters;
        }
        public async Task<string> Save(List<object> parameters)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");  //保存接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();
        }

        public async Task<string> Submit(List<object> parameters)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");  //提交接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();
        }

        public async Task<string> Audit(List<object> parameters)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");  //审核接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();    //审核结果
        }
        public async Task<string> UnAudit(List<object> parameters)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");  //反审核
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();    //审核结果
        }
        public async Task<string> Delete(List<object> parameters)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");  //删除接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();    //删除结果
        }

        public async Task<string> Allocate(List<object> parameters)   //分配
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate.common.kdsvc");  //分配接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();
        }

        public async Task<string> BatchSave(List<object> parameters)   //批量保存
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = string.Concat(K3CloudLogin.CloudUrl, "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc");  //批量保存接口
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            return httpClient.AsyncRequest();
        }
        public string ErrMsg(ErrorMsg.Root err)
        {
            var errlist = err.Result.ResponseStatus.Errors;
            string errmsg = "";
            foreach (var item in errlist)
            {
                errmsg += item.Message + ",";
            }
            errmsg = errmsg.Substring(0, errmsg.Length - 1);
            return errmsg;
        }
    }

}
